/*
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
package com.tlr.device.rest;

import static com.tfb.service.utility.JsonUtil.UTF8;
import com.tfb.service.utility.Utils;
import com.tlr.device.model.Result;
import java.io.File;
import java.io.FileFilter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

@Path("/doc")
public class DocumentFileService {

    private static final Logger log = Logger.getLogger(DocumentFileService.class);

    @GET
    @Path("/download")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response dowloadDocFile(@QueryParam("filename") String fileName) {
        try {
            // TODO
            File downloadFromDir = new File(AppContext.getDocDownloadDir());
            File downloadFile = new File(downloadFromDir + "/" + fileName);
            if (downloadFile.exists()) {
                return Response.ok().header("Content-Disposition",
                                            String.format("attachment; filename=%s;filename*=UTF-8''%s;filename=%s",
                                                          URLEncoder.encode(fileName, UTF8), URLEncoder.encode(fileName, UTF8), fileName))
                        .header("Set-Cookie", "fileDownload=true; Path=/").entity(IOUtils.toByteArray(downloadFile.toURI())).build();
            } else {
                return Response.status(500).entity("路径不存在").build();
            }
        } catch (Exception ex) {
            log.error(Utils.getFullException(ex));
            return Response.status(500).entity("下载文件错误，请联系管理员").build();
        }
    }

    @GET
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
    public Result<List<String>> listDocFiles() {
        File downloadFromDir = new File(AppContext.getDocDownloadDir());
        if (downloadFromDir.exists()) {
            List<String> docList = new ArrayList<>();
            File[] files = downloadFromDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return !f.isHidden();
                }
            });
            for (File f : files) {
                docList.add(f.getName());
                log.info("Doc name: " + f.getName());
            }
            return new Result(0, "OK", docList);
        } else {
            log.error("'" + AppContext.getDocDownloadDir() + "' 不存在！");
        }
        return new Result<>(500, "路径不存在!");
    }

}
